package org.dut.community.actuator;

import lombok.extern.slf4j.Slf4j;
import org.dut.community.util.CommunityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Slf4j
@Component
@Endpoint(id = "database")
public class DataBaseEndPoint {
    @Autowired
    private DataSource dataSource;

    // 尝试访问链接，失败则数据库链接有问题
    // GET请求会调用该方法
    @ReadOperation
    public String checkConnection() {
        try (var ignored = dataSource.getConnection();){
            return CommunityUtil.getJSONString(0,"数据库连接成功");
        } catch (Exception e) {
            log.error("获取数据库连接失败",e);
            return CommunityUtil.getJSONString(1,"数据库连接失败");
        }
    }
}
